package com.sdy.dataexchange.meta.util;

import com.sdy.common.utils.DateUtil;
import com.sdy.dataexchange.meta.model.MetadataJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: 王越洋
 * @version: v1.0
 * @description: com.sdy.dataexchange.meta.util

 * @date:2019/11/15
 */
@Slf4j
@Component
public class CronUtil {

    /**
     *
     * @param mj 任务类
     * @return
     */
    public static String queryData(MetadataJob mj) {
        if (mj!=null){
            String stringDate = "";
            Map<String, Object> dateMap = new HashMap<String, Object>();
            if (mj.getMjobType().equals("2")){
                stringDate =DateUtil.dateToString(mj.getStartTime(),DateUtil.DATETIME_FORMAT);
                dateMap.put("MM", stringDate.substring(5, 7));
                dateMap.put("dd", stringDate.substring(8, 10));
                dateMap.put("HH", stringDate.substring(11, 13));
            }else if (mj.getMjobType().equals("3")){
                stringDate =DateUtil.dateToString(mj.getStartTime(),DateUtil.DATE_FORMAT);
                dateMap.put("MM", stringDate.substring(5, 7));
                dateMap.put("dd", stringDate.substring(8, 10));
            }else if(mj.getMjobType().equals("1")){
                stringDate =DateUtil.dateToString(mj.getStartTime(),DateUtil.DATETIME_FORMAT);
                dateMap.put("MM", stringDate.substring(5, 7));
                dateMap.put("dd", stringDate.substring(8, 10));
                dateMap.put("HH", stringDate.substring(11, 13));
                dateMap.put("mm", stringDate.substring(14, 16));
            }
                return CronUtil.queryCron(mj,dateMap);
        }
        return "时间为空";
    }

    /**
     * 生成 Cron 表达式
     *
     * @param mj 任务类
     * @param dateMap 获取时间参数
     * @return
     */

    private static String queryCron(MetadataJob mj, Map dateMap) {
        String cron = "";
        switch (mj.getMjobMftype()) {
            case 0:
                cron = "0/"+mj.getMjobMf()+" * * * * ? ";
                break;
            case 1:
                cron = "0 0/"+mj.getMjobMf()+" * * * ? *";
                break;
            case 2:
                cron = "0 " + dateMap.get("mm") + " 0/" + mj.getMjobMf() + " * * ? *";
                break;
            case 3:
                cron = "0 " + dateMap.get("mm") + " " + dateMap.get("hh") + " 1/" + mj.getMjobMf() + " * ? ";
                break;
            default:
        }
        return cron;
    }
}
